package vn.orderonline.core.redis.model;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class RedisFactory {

	private JedisPool readPool;
	private JedisPool writePool;
	private int databaseIndex;

	public RedisFactory(RedisConfiguration redisConfiguration) {
		JedisPoolConfig config = new JedisPoolConfig();
		config.setMaxTotal(redisConfiguration.getMaxConnection());

		databaseIndex = redisConfiguration.getDatabaseIndex();
		readPool = new JedisPool(config, redisConfiguration.getReadHost(),
				redisConfiguration.getReadPort());
		writePool = new JedisPool(config, redisConfiguration.getWriteHost(),
				redisConfiguration.getWritePort());
	}
	
	public Jedis getReader() {
		Jedis jedis = readPool.getResource();
		jedis.select(databaseIndex);
		return jedis;
	}
	
	public Jedis getWriter() {
		Jedis jedis = writePool.getResource();
		jedis.select(databaseIndex);
		return jedis;
	}
	
	public void returnReadResource(Jedis jes) {
		if (jes != null) {
			readPool.returnResource(jes);
			jes = null;
		}
	}
	
	public void returnWriteResource(Jedis jes) {
		if (jes != null) {
			writePool.returnResource(jes);
			jes = null;
		}
	}
	
	public void returnBrokenReadResource(Jedis jes) {
		if (jes != null) {
			readPool.returnBrokenResource(jes);
			jes = null;
		}
	}
	
	public void returnBrokenWriteResource(Jedis jes) {
		if (jes != null) {
			writePool.returnBrokenResource(jes);
			jes = null;
		}
	}
	
}
